package com.xjrsoft.module.oa.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageInput;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.erpModel.caseErpSupplier.vo.CaseErpSupplierPageVo;
import com.xjrsoft.module.erpModel.caseErpUnit.entity.CaseErpUnit;
import com.xjrsoft.module.oa.dto.NewsPageDto;
import com.xjrsoft.module.oa.dto.UpdateScheduleDto;
import com.xjrsoft.module.oa.dto.AddScheduleDto;
import com.xjrsoft.module.oa.entity.News;
import com.xjrsoft.module.oa.entity.NewsRelation;
import com.xjrsoft.module.oa.entity.Schedule;
import com.xjrsoft.module.oa.service.IScheduleService;
import com.xjrsoft.module.oa.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.bytebuddy.NamingStrategy;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 日程管理 前端控制器
 * </p>
 *
 * @author zlf
 * @since 2022-06-16
 */
@RestController
@RequestMapping(GlobalConstant.OA_MODULE_PREFIX + "/schedule")
@Api(value = GlobalConstant.OA_MODULE_PREFIX + "/schedule", tags = "日程管理")
@AllArgsConstructor
public class ScheduleController {

    private final IScheduleService scheduleService;

    @GetMapping("/box")
    @ApiOperation(value = "消息提醒处获取日程")
    public R box(PageInput dto) {
        List<Schedule> scheduleList = scheduleService.list(Wrappers.<Schedule>query().lambda()
                .eq(Schedule::getEnabledMark, 1)
                .eq(Schedule::getCreateUserId, StpUtil.getLoginIdAsLong())
                .orderByDesc(Schedule::getCreateDate));
        List<ScheduleBoxVo> scheduleBoxVoList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Schedule schedule : scheduleList) {
            LocalDateTime startDate = schedule.getStartDate();
            LocalDateTime endDate = schedule.getEndDate();//日程结束时间
            ScheduleBoxVo scheduleBoxVo = new ScheduleBoxVo();
            scheduleBoxVo.setId(schedule.getId());
            scheduleBoxVo.setCreateDate(schedule.getCreateDate());
            if (ObjectUtil.isNotEmpty(schedule.getScheduleState()) && schedule.getScheduleState() == YesOrNoEnum.YES.getCode()){//已读
                scheduleBoxVo.setIsRead(true);
            }else {//默认为未读
                scheduleBoxVo.setIsRead(false);
            }
            if (LocalDateTimeUtil.between(now.minusHours(1),endDate).toMinutes() > 0 && LocalDateTimeUtil.between(now,endDate).toMinutes() <= 60){
                //相差的时间小于60分钟
                scheduleBoxVo.setTitle("您的日程在一小时内即将结束，日程内容为:【" + schedule.getScheduleContent()+"】");
                scheduleBoxVoList.add(scheduleBoxVo);
            } else if (LocalDateTimeUtil.between(now,startDate).toMinutes() < 0 && LocalDateTimeUtil.between(now,endDate).toMinutes() > 0) {
                //进行中的,当前时间比开始时间大，比结束时间小
                scheduleBoxVo.setTitle("您的日程【" + schedule.getScheduleContent() + "】已经开始");
                scheduleBoxVoList.add(scheduleBoxVo);
            } else if (LocalDateTimeUtil.between(now.minusDays(1),startDate).toDays() == 1) {
                //当前时间比开始时间小于一天,但大于开始时间
                scheduleBoxVo.setId(schedule.getId());
                scheduleBoxVo.setTitle("您有一项日程在一天后即将开始，日程内容为：【" + schedule.getScheduleContent()+"】");
                scheduleBoxVoList.add(scheduleBoxVo);
            }
        }
        if (StrUtil.isNotBlank(dto.getKeyword())){
            scheduleBoxVoList = scheduleBoxVoList.stream().filter(x -> x.getTitle().contains(dto.getKeyword())).collect(Collectors.toList());
        }
        if (scheduleBoxVoList.size() > 0){
            scheduleBoxVoList.sort((t1,t2)->t2.getCreateDate().compareTo(t1.getCreateDate()));
        }
        PageOutput<ScheduleBoxVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotal(scheduleBoxVoList.size());
        output.setList(scheduleBoxVoList);

        return R.ok(output);
    }

    @GetMapping
    @ApiOperation(value = "获取日程管理列表")
    public R list(PageInput dto) {
        List<Schedule> scheduleList = scheduleService.list(Wrappers.<Schedule>query().lambda()
                .eq(Schedule::getEnabledMark, 1)
                .like(StrUtil.isNotBlank(dto.getKeyword()),Schedule::getScheduleContent,dto.getKeyword())
                .eq(Schedule::getCreateUserId, StpUtil.getLoginIdAsLong())
                .orderByDesc(Schedule::getCreateDate));
        List<ScheduleListVo> scheduleListVos = new ArrayList<>(scheduleList.size());
        for (Schedule schedule : scheduleList) {
            ScheduleListVo scheduleListVo = new ScheduleListVo();
            scheduleListVo.setId(schedule.getId());
            scheduleListVo.setScheduleName(schedule.getScheduleName());
            scheduleListVo.setScheduleContent(schedule.getScheduleContent());
            scheduleListVo.setStart(schedule.getStartDate());
            scheduleListVo.setEnd(schedule.getEndDate());
            scheduleListVo.setAllDay(false);
            scheduleListVo.setTitle(schedule.getScheduleContent());
            scheduleListVos.add(scheduleListVo);
        }
        return R.ok(scheduleListVos);
    }

    @PostMapping
    @ApiOperation(value = "添加日程管理")
    public R add(@RequestBody AddScheduleDto scheduleDto) {
        Schedule schedule = BeanUtil.toBean(scheduleDto, Schedule.class);
        //添加消息通知
        boolean save = scheduleService.save(schedule);
        return R.ok(save);
    }

    @PutMapping
    @ApiOperation(value = "修改日程管理")
    public R update(@RequestBody UpdateScheduleDto scheduleDto) {
        Schedule schedule = BeanUtil.toBean(scheduleDto, Schedule.class);
        return R.ok(scheduleService.updateById(schedule));
    }

    @DeleteMapping
    @ApiOperation(value = "删除日程管理")
    public R delete(@RequestBody List<Long> ids) {
        return R.ok(scheduleService.delete(ids));
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "日程详情")
    public R info(@RequestParam Long id) {
        Schedule schedule = scheduleService.getById(id);
        if (schedule == null) {
            R.error("找不到当前日程！");
        }
        return R.ok(BeanUtil.toBean(schedule, ScheduleVo.class));
    }

    @PutMapping("/read")
    @ApiOperation(value = "日程单个已读")
    public R read(@RequestBody List<Long> ids) {
        List<Schedule> scheduleList = new ArrayList<>(ids.size());
        for (Long id : ids) {
            Schedule schedule = new Schedule();
            schedule.setId(id);
            schedule.setScheduleState(YesOrNoEnum.YES.getCode());
            scheduleList.add(schedule);
        }
        return R.ok(scheduleService.updateBatchById(scheduleList));
    }

    @PutMapping("/all-read")
    @ApiOperation(value = "日程全部已读")
    public R allRead() {
        scheduleService.update(Wrappers.<Schedule>lambdaUpdate()
                .eq(Schedule::getCreateUserId, StpUtil.getLoginIdAsLong())
                .eq(Schedule::getEnabledMark, 1)
                .set(Schedule::getScheduleState, YesOrNoEnum.YES.getCode()));
        return R.ok(true);
    }
}
